package group2assignone.ucm.customer;

import group2assignone.dao.MyDAO;
import group2assignone.model.Customer;
import group2assignone.ucm.UCController;
import group2assignone.ucm.UCStartup;
import group2assignone.view.MainView;
import group2assignone.view.UITool;
import group2assignone.view.customer.CustomerWelcomeView;
import javax.swing.JOptionPane;

/**
 *Use Case Controller - allows the user to delete their account once
 * they are logged in.
 */
public class UCDeleteCustomer implements UCController {

    private Customer cust;
    private CustomerWelcomeView view;
    private boolean okDAO;
    private int option;

    /**
     * sets the customer and view, used for personalisation
     * @param cust
     * @param view
     */
    public UCDeleteCustomer(Customer cust, CustomerWelcomeView view) {
        this.cust = cust;
        this.view = view;
    }

    /**
     * Use Case: Delete Customer Account
     * Pre-Condition: CustomerWelcomeView UI, user is logged in 
     * Post-Condition: UI is updated
     * 1. User selects 'Delete Account'
     * 2. System requests confirmation from user
     * 3. User confirms
     * 4. System deletes account 
     * 5. System 'logs out' user and updates UI
     * 4a. - System cannot access account to delete it (connection error etc)
     *     - System displays error message
     *     - System updates UI to CustomerWelcomeView
     */
    public void run() {
        option = view.confirmDelete();
        if (option == JOptionPane.YES_OPTION) {
            MyDAO coms = UCStartup.getInstance().getDAO();
            okDAO = coms.sQLDeleteCustomer(cust.getUsername());
            okDAO = true;//delete account from database (call function from DAO, return ok)
            if (okDAO) {
                view.notifyDelete();
                MainView gui = new MainView();
                gui.go();
                view.dispose();
            } else {
                UITool.displayError("Cannot connect to database at this time. Try again later.", view);
            }
        }
    }
}
